package com.huashi.dealer.modular.controller.store.message;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.MessageCategory;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.article.param.*;
import com.huashi.dealer.modular.business.article.service.StoreArticleService;
import com.huashi.dealer.modular.business.article.service.ArticleCategoryService;
import com.huashi.dealer.modular.business.article.vo.StoreArticleListVo;
import com.huashi.dealer.commonEntity.ArticleCategory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huashi.dealer.modular.business.message.param.ArticleCategoryBo;
import com.huashi.dealer.modular.business.message.param.StoreMessageListParam;
import com.huashi.dealer.modular.business.message.param.MessageResponseParam;
import com.huashi.dealer.modular.business.message.service.MessageCategoryService;
import com.huashi.dealer.modular.business.message.service.MessageService;
import com.huashi.dealer.commonEntity.Message;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Store端文章管理（对应PHP的 /store/content.article/index）
 */
@Slf4j
@RestController
@RequestMapping("/store/content/article")
@Tag(name = "Store端文章管理", description = "文章列表等功能，对应PHP /store/content.article/index")
@Validated
public class ArticleController {

    @Resource
    private StoreArticleService storeArticleService;
    @Resource
    private ArticleCategoryService articleCategoryService;
    @Resource
    private MessageService messageService;
    @Autowired
    private MessageCategoryService messageCategoryService;

    /**
     * 文章列表（默认按article_sort升序、create_time降序，is_delete=0）
     */
    @GetMapping("/list")
    @Operation(summary = "文章列表", description = "获取文章列表，支持按分类与标题筛选")
    public CommonResult<Page<StoreArticleListVo>> index(@Parameter(description = "查询参数") @Valid StoreArticleListParam param) {
        try {
            Page<StoreArticleListVo> page = PageFactory.defaultPage();
            Page<StoreArticleListVo> result = storeArticleService.getArticlePage(param, page);
            return CommonResult.data(result);
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return CommonResult.error("获取文章列表失败：" + e.getMessage());
        }
    }

    /**
     * 消息列表（对应PHP的 /store/content.message/index）
     */
    @GetMapping("/message/list")
    @Operation(summary = "消息列表", description = "按类型/分类/标题分页查询消息")
    public CommonResult<Page<Message>> messageList(@Valid StoreMessageListParam param) {

        try {
            param.setIsType(10);
            Page<Message> page = PageFactory.defaultPage();
            page=messageService.getMessageList(param,page);
            return CommonResult.data(page);
        } catch (Exception e) {
            log.error("获取消息列表失败", e);
            return CommonResult.error("获取消息列表失败：" + e.getMessage());
        }
    }

    /**
     * 消息保存（新增/编辑合一）
     */
    @PostMapping("/message/save")
    @Operation(summary = "消息保存(新增/编辑)")
    public CommonResult<String> messageSave(@RequestBody Message param) {
        try {
            param.setIsType(10);
            messageService.saveOrEditMessage(param);
            return CommonResult.ok("保存成功");
        } catch (Exception e) {
            log.error("保存消息失败", e);
            return CommonResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 消息删除
     */
    @GetMapping("/message/delete/{messageId}")
    @Operation(summary = "消息删除")
    public CommonResult<String> messageDelete(@PathVariable Long messageId) {
        try {
            messageService.deleteMessage(messageId);
            return CommonResult.ok("删除成功");
        } catch (Exception e) {
            log.error("删除消息失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取消息详情（用于编辑回显）
     * 对应PHP的 /store/content.message/edit 接口的回显部分
     */
    @GetMapping("/message/detail/{messageId}")
    @Operation(summary = "获取消息详情", description = "用于编辑页面回显消息详细信息")
    public CommonResult<MessageResponseParam> messageDetail(@Parameter(description = "消息ID") @PathVariable Long messageId) {
        try {
            MessageResponseParam detail = messageService.getMessageDetail(messageId);
            return CommonResult.data(detail);
        } catch (Exception e) {
            log.error("获取消息详情失败", e);
            return CommonResult.error("获取消息详情失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告列表（对应PHP的 /store/content.company/index）
     */
    @GetMapping("/company/list")
    @Operation(summary = "公司公告列表", description = "按类型/分类/标题分页查询公司公告")
    public CommonResult<Page<Message>> companyList(@Valid StoreMessageListParam param) {
        try {
            // 公司公告固定为is_type=20
            param.setIsType(20);
            Page<Message> page = PageFactory.defaultPage();
            page = messageService.getMessageList(param, page);
            return CommonResult.data(page);
        } catch (Exception e) {
            log.error("获取公司公告列表失败", e);
            return CommonResult.error("获取公司公告列表失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告保存（新增/编辑合一）
     */
    @PostMapping("/company/save")
    @Operation(summary = "公司公告保存(新增/编辑)")
    public CommonResult<String> companySave(@RequestBody MessageBo bo) {
        Message param = new Message();
        BeanUtils.copyProperties(bo, param);
        try {
            // 公司公告固定为is_type=20
            param.setIsType(20);
            messageService.saveOrEditMessage(param);
            return CommonResult.ok("保存成功");
        } catch (Exception e) {
            log.error("保存公司公告失败", e);
            return CommonResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告删除
     */
    @GetMapping("/company/delete/{messageId}")
    @Operation(summary = "公司公告删除")
    public CommonResult<String> companyDelete(@PathVariable Long messageId) {
        try {
            messageService.deleteMessage(messageId);
            return CommonResult.ok("删除成功");
        } catch (Exception e) {
            log.error("删除公司公告失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取公司公告详情（用于编辑回显）
     * 对应PHP的 /store/content.company/edit 接口的回显部分
     */
    @GetMapping("/company/detail/{messageId}")
    @Operation(summary = "获取公司公告详情", description = "用于编辑页面回显公司公告详细信息")
    public CommonResult<MessageResponseParam> companyDetail(@Parameter(description = "公司公告ID") @PathVariable Long messageId) {
        try {
            MessageResponseParam detail = messageService.getMessageDetail(messageId);
            return CommonResult.data(detail);
        } catch (Exception e) {
            log.error("获取公司公告详情失败", e);
            return CommonResult.error("获取公司公告详情失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告分类列表（对应PHP的 /store/content.message.category/companyindex）
     */
    @GetMapping("/company/category/list")
    @Operation(summary = "公司公告分类列表(分页)", description = "按sort升序返回公司公告分类分页列表")
    public CommonResult<Page<MessageCategoryVo>> companyCategoryList() {
        try {
            Page<MessageCategory> page = PageFactory.defaultPage();
            LambdaQueryWrapper<MessageCategory> qw = new LambdaQueryWrapper<>();
            qw.eq(MessageCategory::getIsType, 20) // 公司公告分类固定为is_type=20
              .orderByAsc(MessageCategory::getSort);
            Page<MessageCategory> result = messageCategoryService.page(page, qw);
            Page<MessageCategoryVo> page2 = new Page<>();
            BeanUtils.copyProperties(result, page2);
            List<MessageCategoryVo> voList = result.getRecords().stream().map(r -> {
                MessageCategoryVo vo = new MessageCategoryVo();
                BeanUtils.copyProperties(r, vo);
                return vo;
            }).collect(Collectors.toList());
            page2.setRecords(voList);
            return CommonResult.data(page2);
        } catch (Exception e) {
            log.error("获取公司公告分类列表失败", e);
            return CommonResult.error("获取公司公告分类列表失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告分类新增/编辑（同一个接口）
     */
    @PostMapping("/company/category/save")
    @Operation(summary = "公司公告分类新增/编辑")
    public CommonResult<String> saveCompanyCategory(@RequestBody MessageCategorySaveBo bo) {
        MessageCategory param = new MessageCategory();
        BeanUtils.copyProperties(bo, param);
        try {
            // 公司公告分类固定为is_type=20
            param.setIsType(20);
            if(param.getCategoryId() == null){
                param.setCreateTime(System.currentTimeMillis() /1000);
                param.setUpdateTime(System.currentTimeMillis() /1000);
            }else{
                param.setUpdateTime(System.currentTimeMillis() /1000);
            }
            boolean ok = messageCategoryService.saveOrUpdate(param);
            return ok ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
        } catch (Exception e) {
            log.error("保存公司公告分类失败", e);
            return CommonResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 公司公告分类删除
     */
    @GetMapping("/company/category/delete/{categoryId}")
    @Operation(summary = "公司公告分类删除")
    public CommonResult<String> deleteCompanyCategory(@PathVariable Long categoryId) {
        try {
            boolean ok = messageCategoryService.removeById(categoryId);
            return ok ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
        } catch (Exception e) {
            log.error("删除公司公告分类失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 文章分类列表（对应PHP的 /store/content.article.category/index）
     */
    @GetMapping("/category/list")
    @Operation(summary = "文章分类列表(分页)", description = "按sort升序返回文章分类分页列表")
    public CommonResult<Page<ArticleCategory>> categoryList() {
        try {
            Page<ArticleCategory> page = PageFactory.defaultPage();
            LambdaQueryWrapper<ArticleCategory> qw = new LambdaQueryWrapper<>();
            qw.orderByAsc(ArticleCategory::getSort);
            Page<ArticleCategory> result = articleCategoryService.page(page, qw);
            return CommonResult.data(result);
        } catch (Exception e) {
            log.error("获取文章分类列表失败", e);
            return CommonResult.error("获取文章分类列表失败：" + e.getMessage());
        }
    }

    /**
     * 文章分类新增/编辑（同一个接口）
     */
    @PostMapping("/policy/save")
    @Operation(summary = "文章分类新增/编辑")
    public CommonResult<String> savePolicy(@RequestBody MessageCategorySaveBo param) {
        MessageCategory messageCategory = new MessageCategory();
        BeanUtils.copyProperties(param, messageCategory);
        try {
            if(param.getCategoryId() == null){
                messageCategory.setCreateTime(System.currentTimeMillis()/1000);
                messageCategory.setUpdateTime(System.currentTimeMillis()/1000);
            }else{
                messageCategory.setUpdateTime(System.currentTimeMillis()/1000);
            }
            messageCategory.setIsType(10);
            boolean ok = messageCategoryService.saveOrUpdate(messageCategory);
            return ok ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
        } catch (Exception e) {
            log.error("保存文章分类失败", e);
            return CommonResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 文章分类删除
     */
    @GetMapping("/policy/delete/{categoryId}")
    @Operation(summary = "文章分类删除")
    public CommonResult<String> deletePolicy(@PathVariable Long categoryId) {
        try {
            boolean ok = messageCategoryService.removeById(categoryId);
            return ok ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
        } catch (Exception e) {
            log.error("删除文章分类失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 文章分类新增/编辑（同一个接口）
     */
    @PostMapping("/category/save")
    @Operation(summary = "文章分类新增/编辑")
    public CommonResult<String> saveCategory(@RequestBody ArticleCategoryBo param) {
        try {
            if(param.getCategoryId() == null){
                param.setCreateTime((System.currentTimeMillis()/1000));
                param.setUpdateTime((System.currentTimeMillis()/1000));
            }else{
                param.setUpdateTime(((System.currentTimeMillis()/1000)));
            }
            log.info("保存文章分类：{}", param);
            ArticleCategory articleCategory = new ArticleCategory();
            BeanUtils.copyProperties(param, articleCategory);
            boolean ok = articleCategoryService.saveOrUpdate(articleCategory);
            return ok ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
        } catch (Exception e) {
            log.error("保存文章分类失败", e);
            return CommonResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 文章分类删除
     */
    @GetMapping("/category/delete/{categoryId}")
    @Operation(summary = "文章分类删除")
    public CommonResult<String> deleteCategory(@PathVariable Long categoryId) {
        try {
            boolean ok = articleCategoryService.removeById(categoryId);
            return ok ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
        } catch (Exception e) {
            log.error("删除文章分类失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /** 新增文章 */
    @PostMapping("/add")
    @Operation(summary = "新增文章")
    public CommonResult<String> add(@Valid @RequestBody StoreArticleAddParam param) {
        try {
            storeArticleService.addArticle(param);
            return CommonResult.ok("添加成功");
        } catch (Exception e) {
            log.error("新增文章失败", e);
            return CommonResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 消息首页
     */
    @GetMapping("/index/{type}")
    @Operation(summary = "消息首页")
    public CommonResult<List<MessageCategory>> getMessageIndex(@PathVariable String type) {
        try {
            List<MessageCategory> responseParam = messageService.getMessageIndex(type);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取消息首页失败：" + e.getMessage());
        }
    }

    /** 编辑文章 */
    @PostMapping("/edit")
    @Operation(summary = "编辑文章")
    public CommonResult<String> edit(@Valid @RequestBody StoreArticleEditParam param) {
        try {
            storeArticleService.editArticle(param);
            return CommonResult.ok("更新成功");
        } catch (Exception e) {
            log.error("编辑文章失败", e);
            return CommonResult.error("更新失败：" + e.getMessage());
        }
    }

    /** 删除文章（软删） */
    @GetMapping("/delete/{articleId}")
    @Operation(summary = "删除文章")
    public CommonResult<String> delete(@PathVariable Long articleId) {
        try {
            storeArticleService.deleteArticle(articleId);
            return CommonResult.ok("删除成功");
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取文章详情（用于编辑回显）
     * 对应PHP的 /store/content.article/edit 接口的回显部分
     */
    @GetMapping("/detail/{articleId}")
    @Operation(summary = "获取文章详情", description = "用于编辑页面回显文章详细信息")
    public CommonResult<StoreArticleListVo> detail(@Parameter(description = "文章ID") @PathVariable Long articleId) {
        try {
            StoreArticleListVo detail = storeArticleService.getArticleDetail(articleId);
            return CommonResult.data(detail);
        } catch (Exception e) {
            log.error("获取文章详情失败", e);
            return CommonResult.error("获取文章详情失败：" + e.getMessage());
        }
    }
}


